<?php
// +----------------------------------------------------------------------
// | Author: heizai <876555425@qq.com>
// +----------------------------------------------------------------------
namespace plugins\hz_msg_borad\controller;

use cmf\controller\PluginBaseController;
use plugins\hz_msg_borad\model\PluginMessageModel;
use think\Db;
use PHPExcel_IOFactory;
use PHPExcel;

class DoController extends PluginBaseController
{

    // 前台留言提交
    public function addhomemsg()
    {
        if ($this->request->isPost()) {
            $model = new PluginMessageModel();
            $data = $this->request->post();
            $result = $this->validate($data, "Post");

            if ($result !== true) {
                $this->error($result);
            }
            if(!cmf_captcha_check($data['verify'])){
                $this->error("验证码错误！");
            }

            $data['createtime'] = date('Y-m-d H:i:s');
            $result = $model->allowField(true)->save($data);

            if ($result !== false) {
                $this->success("留言成功！");
            } else {
                $this->error("留言失败！");
            }
        }
        echo $this->fetch();
    }

    /**
     * 后台
     */
    public function addmsg()
    {
        if ($this->request->isPost()) {
            $model = new PluginMessageModel();
            $data = $this->request->post();
            $result = $this->validate($data, "Post");

            if ($result !== true) {
                $this->error($result);
            }
            $data['createtime'] = date('Y-m-d H:i:s');
            $result = $model->allowField(true)->save($data);

            if ($result !== false) {
                //$this->success("留言成功！");
                $this->redirect('/plugin/hz_msg_borad/admin_index/index');
            } else {
                $this->error("留言失败！");
            }
        }
        echo $this->fetch();
    }

    /**
     * 接口地址 http://xxx.com/plugin/hz_msg_borad/do/apiaddmsg
     * type post
     * params article_id,name,avatar,email,phone,title,msg
     * 必填参数 msg
     */
    public function apiaddmsg()
    {
        if ($this->request->isPost()) {
            $model = new PluginMessageModel();
            $data = $this->request->post();
            $result = $this->validate($data, "Post");

            if ($result !== true) {
                echo json_encode([
                    'code'=>201,
                    'msg'=>$result
                ]);
                exit;
            }

            $data['createtime'] = date('Y-m-d H:i:s');
            $result = $model->allowField(true)->save($data);

            if ($result !== false) {
                echo json_encode([
                    'code'=>200,
                    'msg'=>'ok'
                ]);
                exit;
            } else {
                echo json_encode([
                    'code'=>201,
                    'msg'=>'error'
                ]);
                exit;
            }
        }
    }

    public function delete()
    {
        $id = $this->request->get('id');
        PluginMessageModel::where(['id' => $id])->delete();
        $this->redirect('/plugin/hz_msg_borad/admin_index/index');
    }

    public function downmodel(){
        $data = [
            [
                "article_id"=>"article_id",
                "name" => "name",
                "avatar" => "avatar",
                "email" => "email",
                "phone" => "phone",
                "title" => "title",
                "msg" => "msg",
            ],
            [
                "article_id"=>1,
                "name" => "admin",
                "avatar" => "/plugins/hz_msg_borad/view/public/assets/images/default.jpg",
                "email" => "admin@admin.com",
                "phone" => "123456",
                "title" => "我是帅哥",
                "msg" => "帅哥是谁",
            ]
        ];
        $name = "msg";
        error_reporting(E_ALL);
        date_default_timezone_set('Europe/London');
        $objPHPExcel = new PHPExcel();
        /*以下就是对处理Excel里的数据， 横着取数据，主要是这一步，其他基本都不要改*/
        foreach($data as $k => $v){

            $num=$k+1;
            $objPHPExcel->setActiveSheetIndex(0)//Excel的第A列，uid是你查出数组的键值，下面以此类推
            ->setCellValue('A'.$num, $v['article_id'])
                ->setCellValue('B'.$num, $v['name'])
                ->setCellValue('C'.$num, $v['avatar'])
                ->setCellValue('D'.$num, $v['email'])
                ->setCellValue('E'.$num, $v['phone'])
                ->setCellValue('F'.$num, $v['title'])
                ->setCellValue('G'.$num, $v['msg']);
        }

        $objPHPExcel->getActiveSheet()->setTitle('User');
        $objPHPExcel->setActiveSheetIndex(0);
        header('Content-Type: applicationnd.ms-excel');
        header('Content-Disposition: attachment;filename="'.$name.'.xls"');
        header('Cache-Control: max-age=0');
        $objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel5');
        $objWriter->save('php://output');
        exit;
    }

    public function batchmsg()
    {
        $filepath = APP_PATH . '../public' . $this->request->post('filepath');

        $obj_PHPExcel = PHPExcel_IOFactory::load($filepath); //加载文件

        $type = 'Excel2007';//设置为Excel5代表支持2003或以下版本，Excel2007代表2007版
        $xlsReader = PHPExcel_IOFactory::createReader($type);
        $xlsReader->setReadDataOnly(true);
        $xlsReader->setLoadSheetsOnly(true);

        $data = $obj_PHPExcel->getSheet(0)->toArray();

        foreach ($data as $key => $value) {
            if ($key == 0) {
                continue;
            }
            $data2[] = [
                "article_id" => $value[0],
                "name" => $value[1],
                "avatar" => $value[2],
                "email" => $value[3],
                "phone" => $value[4],
                "title" => $value[5],
                "msg" => $value[6],
                "createtime" => date('Y-m-d H:i:s')
            ];
        }

        $model = new PluginMessageModel();
        if ($model->allowField(true)->saveAll($data2)) {
            $this->success("导入成功");
        } else {
            $this->error("导入失败");
        }
    }

}
